import React, { Component } from 'react'
import { StyleSheet, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { Chats, IconButton } from '../components'

export const CHATS_QUERY = gql`
  query {
    user {
      id
      chats {
        id
        name
        members {
          id
          name
        }
        messages(last: 1) {
          id
          from {
            id
            name
          }
          content
          createdAt
        }
      }
    }
  }
`

@inject('actions', 'store')
@observer
@graphql(CHATS_QUERY, { options: { fetchPolicy: 'network-only' } })
export class ChatsScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerLeft: (
      <IconButton name="list" onPress={() => navigation.navigate('Contacts')} />
    ),
    // headerRight: <IconButton name="add" onPress={() => console.warn('TODO')} />,
  })

  render = () => (
    <View style={styles.container}>
      <Chats
        chats={this.props.data.loading ? [] : this.props.data.user.chats}
        self={this.props.store.user}
        loading={this.props.data.loading}
        onRefresh={this.props.data.refetch}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
})
